package com.ktwlsoft.fundmanage.domain.repository;

import com.ktwlsoft.fundmanage.domain.entity.BaseFundRecord;
import com.ktwlsoft.fundmanage.domain.entity.FundInRecord;
import com.ktwlsoft.fundmanage.domain.entity.FundOutRecord;
import com.ktwlsoft.fundmanage.domain.entity.BaseFundRecord.State;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

public interface FundInRecordRepository extends JpaRepository<FundInRecord, Long> {

    @Modifying
    @Query("update FundInRecord r set r.payCheck = :approval, r.payChecker = :auditor, r.payCheckerId = :auditorId, r.state=:state, r.payCheckTime=:checkTime" +
            " where r.fCode=:fcode")
    int setFundInCheck(boolean approval, long fcode, String auditor, String auditorId, BaseFundRecord.State state, Date checkTime);

    List<FundInRecord> findByTsCode(long tsCode);

    List<FundInRecord> findByTsCodeAndType(long tsCode, BaseFundRecord.Type type);

    @Query("select sum(f.amount) from FundInRecord f where f.tsCode = :tsCode and f.type = 'DOWNPAY'")
    BigDecimal queryDownPay(long tsCode);

    @Query("select sum(f.amount) from FundInRecord f where f.tsCode = :tsCode and f.type = 'LOAN'")
    BigDecimal queryLoan(long tsCode);

    @Modifying
    @Query("update FundInRecord r set r.payCheck = false, r.isReturn = true, r.state='CANCEL', r.flowInstanceId = :processInstanceId where r.fCode=:id")
    int cancelAccountCheck(long id, String processInstanceId);

    List<FundInRecord> findByFCode(Long fCode);

    List<FundInRecord> findByDnCode(long transId);

    List<FundInRecord> findByNetSignCode(String netcodesign);

    List<FundInRecord> findByStateAndUserId(BaseFundRecord.State state, String userId);

    @Modifying
    @Query("update FundInRecord f set f.hasTransfer = f.hasTransfer-:amount where f.fCode=:fCode")
    int restoreTransferedAmount(BigDecimal amount, long fCode);

    @Modifying
    @Query("update FundInRecord f set f.hasTransfer = f.hasTransfer+:amount where f.fCode=:fCode")
    int transferedAmount(BigDecimal amount, long fCode);

    @Modifying
    @Query("update FundInRecord f set f.transferd = :isTransfer where f.fCode=:fCode")
    int updateFundInTransfered(long fCode, boolean isTransfer);

    @Query("select sum(f.amount) from FundInRecord f where f.tsCode = :tsCode")
    BigDecimal getPayAll(long tsCode);

    boolean existsByTypeAndStateAndTsCode(BaseFundRecord.Type type, BaseFundRecord.State state, long tsCode);

    boolean existsByTypeAndStateAndTsCodeAndPayCheck(BaseFundRecord.Type type, BaseFundRecord.State state, long tsCode, boolean check);

}
